/**
 * Copyright (c) 2014- 2015 YCY Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.jkwzms.system.auth.web.controller;

import java.util.Map;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.jkwzms.common.entity.search.SearchOperator;
import com.jkwzms.common.entity.search.Searchable;
import com.jkwzms.common.inject.annotation.BaseComponent;
import com.jkwzms.common.utils.EasyUiMsg;
import com.jkwzms.common.web.controller.BaseCRUDController;
import com.jkwzms.system.auth.entity.Auth;
import com.jkwzms.system.auth.entity.AuthType;
import com.jkwzms.system.auth.service.AuthService;
import com.jkwzms.system.group.entity.GroupType;
import com.jkwzms.system.group.service.GroupService;
import com.jkwzms.system.permission.service.RoleService;

/**
 * <p>
 * User: Jack Liang
 * <p>
 * Date: 13-1-28 下午4:29
 * <p>
 * Version:1.0.0
 */
@Controller
@RequestMapping(value = "/sys/auth")
public class AuthController extends BaseCRUDController<Auth, Long> {

    @Autowired
    @BaseComponent
    private AuthService  authService;

    @Autowired
    private RoleService  roleService;

    @Autowired
    private GroupService groupService;

    public AuthController(){
        setListAlsoSetCommonData(true);
        setResourceIdentity("sys:auth");
    }

    @Override
    protected void setCommonData(Model model) {
        super.setCommonData(model);
        model.addAttribute("types", AuthType.values());

        Searchable searchable = Searchable.newSearchable();
        // searchable.addSearchFilter("show", SearchOperator.eq, true);
        model.addAttribute("roles", roleService.findAllWithNoPageNoSort(searchable));

        // 用户分组信息
        Searchable searchable1 = Searchable.newSearchable();
        searchable1.addSearchFilter("type", SearchOperator.eq, GroupType.user);
        searchable1.addSearchFilter("show", SearchOperator.eq, true);

        model.addAttribute("userGroups", this.groupService.findAllWithNoPageNoSort(searchable1));

    }

    /**
     * to list page
     * 
     * @return
     */
    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String main() {
        return viewName("list");
    }

    @RequestMapping(value = "create/discarded", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        throw new RuntimeException("discard method");
    }

    @RequestMapping(value = "create/discarded", method = RequestMethod.POST)
    public Map<String, Object> create(Model model, @Valid @ModelAttribute("m") Auth m, BindingResult result,
                                      RedirectAttributes redirectAttributes) {
        throw new RuntimeException("discard method");
    }

    @RequestMapping(value = "{type}/create", method = RequestMethod.GET)
    public String showCreateFormWithType(@PathVariable("type") AuthType type, Model model) {
        Auth auth = new Auth();
        auth.setType(type);
        model.addAttribute("m", auth);
        return super.showCreateForm(model);
    }

    /**
     * @param model
     * @param userIds
     * @param groupIds
     * @param organizationIds
     * @param jobIds
     * @param m
     * @param result
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "{type}/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createWithType(Model model,
                                              @RequestParam(value = "userIds", required = false) Long[] userIds,
                                              @RequestParam(value = "groupIds", required = false) Long[] groupIds,
                                              @RequestParam(value = "organizationIds", required = false) Long[] organizationIds,
                                              @RequestParam(value = "jobIds", required = false) Long[][] jobIds,
                                              @Valid @ModelAttribute("m") Auth m, BindingResult result,
                                              RedirectAttributes redirectAttributes) {
        if (permissionList != null) {
            this.permissionList.assertHasCreatePermission();
        }

        if (hasError(m, result)) {
            return EasyUiMsg.successMsg(false);
        }

        if (m.getType() == AuthType.user) {
            authService.addUserAuth(userIds, m);
        } else if (m.getType() == AuthType.user_group || m.getType() == AuthType.organization_group) {
            authService.addGroupAuth(groupIds, m);
        } else if (m.getType() == AuthType.organization_job) {
            authService.addOrganizationJobAuth(organizationIds, jobIds, m);
        }
        return EasyUiMsg.successMsg(true);
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(Model model,
                                      @RequestParam(value = "userIds", required = false) Long[] userIds,
                                      @RequestParam(value = "groupIds", required = false) Long[] groupIds,
                                      @RequestParam(value = "organizationIds", required = false) Long[] organizationIds,
                                      @RequestParam(value = "jobIds", required = false) Long[][] jobIds,
                                      @Valid @ModelAttribute("m") Auth m, BindingResult result) {
        if (permissionList != null) {
            this.permissionList.assertHasUpdatePermission();
        }

        if (hasError(m, result)) {
            return EasyUiMsg.successMsg(false);
        }
        this.authService.update(m);
        if (m.getType() == AuthType.user) {
            authService.updateUserAuth(userIds, m);
        } else if (m.getType() == AuthType.user_group || m.getType() == AuthType.organization_group) {
            authService.addGroupAuth(groupIds, m);
        } else if (m.getType() == AuthType.organization_job) {
            authService.addOrganizationJobAuth(organizationIds, jobIds, m);
        }
        return EasyUiMsg.successMsg(true);
    }

}
